<script setup lang="ts">

import MaForm from "@cps/ma-crud/components/form.vue";
import {computed, nextTick, provide, ref, watch} from "vue";

const useAddForm = () => {
// 按照惯例，组合式函数名以“use”开头
  const defaultConfig = ref({
    width: 100,
    isFull: false,
    title: "",
    columns: [],
    infoColumns: [],
    infoData: {},
    visible: false,
    options: {},
    submit: () => {
      console.log("submit")
    },
  })
  const config = ref({})
  const data = ref({})
  const api = ref()
  const title = ref()
  const addFormConfig = ref({})
  addFormConfig.value.config = computed(()=>{
    return {
      ...defaultConfig.value,
      ...config.value,
    }
  })
  addFormConfig.value.setData = (v) => {
    data.value = v
    return addFormConfig
  }
  addFormConfig.value.setConfig = (v) => {
    config.value = v
    return addFormConfig
  }
  addFormConfig.value.setApi = (v) => {
    api.value = v
    return addFormConfig
  }
  addFormConfig.value.open = async (formRef, api = {}, data = {}, userConfig = {}) => {
    await nextTick();
    if(userConfig){
      config.value = userConfig
    }
    formRef.value.add()
    return addFormConfig
  }
  // 通过返回值暴露所管理的状态
  return {addFormConfig, config }
  // 被组合式函数封装和管理的状态

  // 组合式函数可以随时更改其状态。

  // 一个组合式函数也可以挂靠在所属组件的生命周期上
  // 来启动和卸载副作用
  // onMounted(() => window.addEventListener('mousemove', update))
  // onUnmounted(() => window.removeEventListener('mousemove', update))

}
const {addFormConfig} = useAddForm()
const addFormRef = ref()
const config = ref({})
const successCall = ref()
const templateColumns = ref([]);
const options = ref({
  formOption: {},
  add: {
    title: '新增',
    api:null,
  }
});
const open = (columns,formOption,api,title='新增',success,download) => {
  formOption && (options.value.formOption = formOption)
  columns && (templateColumns.value = columns)
  api && (options.value.add.api = api)
  title && (options.value.add.title = title)
  successCall.value = success
  addFormConfig.value.open(addFormRef)
}

provide('options', options.value)
provide('columns', templateColumns)
defineExpose({
  open,
  config
})
</script>

<template>
  <MaForm v-bind="config" ref="addFormRef" @success="successCall"></MaForm>
</template>

<style scoped>

</style>